from django.contrib.auth.decorators import login_required
from django.db import transaction
from django.shortcuts import render

from django.contrib.auth.password_validation import validate_password
from django.core.exceptions import ValidationError
from django.shortcuts import render, redirect
from django.http import JsonResponse
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password
from .models import VerificationCode
from psychology_login.models import User
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile

import json
import random
import string
from datetime import datetime, timedelta
import re
import os



@login_required(login_url="/login")
def profile(request):
    """
    用户资料页面
    """
    user = request.user.id
    # 获取或创建用户资料
    profile, created = User.objects.get_or_create(id=user)

    context = {
        'user': user,
        'profile': profile,
    }
    return render(request, "profile_page.html", context)


@csrf_exempt
@require_POST
def send_verification_code(request):
    """
    发送验证码到新手机号
    """
    try:
        data = json.loads(request.body)
        phone = data.get('phone')

        # 验证手机号格式
        if not phone or not re.match(r'^1[3-9]\d{9}$', phone):
            return JsonResponse({
                'success': False,
                'message': '请输入有效的手机号码'
            })

        # 检查是否与当前手机号相同
        profile, created = User.objects.get_or_create(user=request.user)
        if profile.phone == phone:
            return JsonResponse({
                'success': False,
                'message': '新手机号不能与当前手机号相同'
            })

        # 生成6位数字验证码
        verification_code = ''.join(random.choices(string.digits, k=6))

        # 存储验证码到数据库
        VerificationCode.objects.create(
            phone=phone,
            code=verification_code,
            user=request.user
        )

        # 这里应该调用短信服务发送验证码
        # 例如：send_sms(phone, f"您的验证码是：{verification_code}")
        print(f"验证码已发送到 {phone}: {verification_code}")

        return JsonResponse({
            'success': True,
            'message': '验证码已发送',
            'dev_code': verification_code  # 开发环境显示验证码
        })

    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': '请求数据格式错误'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': '发送验证码失败，请稍后重试'
        })


@login_required
@require_POST
def update_basic_info(request):
    """
    更新用户基本信息
    """
    try:
        data = json.loads(request.body)
        real_name = data.get('real_name', '').strip()
        region = data.get('region', '').strip()
        school = data.get('school', '').strip()
        print(real_name, region, school)
        # 验证姓名
        if not real_name:
            return JsonResponse({
                'success': False,
                'message': '姓名不能为空'
            })

        if len(real_name) > 50:
            return JsonResponse({
                'success': False,
                'message': '姓名长度不能超过50个字符'
            })

        # 获取或创建用户资料
        profile, created = User.objects.get_or_create(id=request.user.id)

        # 更新用户信息
        profile.first_name = real_name
        profile.region = region
        profile.school = school
        profile.save()

        return JsonResponse({
            'success': True,
            'message': '基本信息更新成功'
        })

    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': '请求数据格式错误'
        })
    except Exception as e:
        print(e)
        return JsonResponse({
            'success': False,
            'message': '更新失败，请稍后重试'
        })


@login_required
@require_POST
def update_phone(request):
    """
    更新用户手机号码
    """
    try:
        data = json.loads(request.body)
        new_phone = data.get('new_phone', '').strip()
        verification_code = data.get('verification_code', '').strip()

        # 验证手机号格式
        if not new_phone or not re.match(r'^1[3-9]\d{9}$', new_phone):
            return JsonResponse({
                'success': False,
                'message': '请输入有效的手机号码'
            })

        # 验证验证码
        if not verification_code or len(verification_code) != 6:
            return JsonResponse({
                'success': False,
                'message': '请输入6位验证码'
            })

        # 检查验证码是否有效
        try:
            verification = VerificationCode.objects.filter(
                phone=new_phone,
                user=request.user,
                is_used=False
            ).latest('created_at')
        except VerificationCode.DoesNotExist:
            return JsonResponse({
                'success': False,
                'message': '请先发送验证码'
            })

        # 检查验证码是否过期（5分钟）
        if verification.is_expired():
            verification.delete()
            return JsonResponse({
                'success': False,
                'message': '验证码已过期，请重新发送'
            })

        # 检查验证码是否正确
        if verification.code != verification_code:
            return JsonResponse({
                'success': False,
                'message': '验证码错误'
            })

        # 检查手机号是否已被其他用户使用
        if User.objects.filter(phone=new_phone).exclude(user=request.user).exists():
            return JsonResponse({
                'success': False,
                'message': '该手机号已被其他用户使用'
            })

        # 获取或创建用户资料
        profile, created = User.objects.get_or_create(user=request.user)

        # 更新用户手机号
        profile.phone = new_phone
        profile.save()

        # 标记验证码为已使用
        verification.is_used = True
        verification.save()

        return JsonResponse({
            'success': True,
            'message': '手机号码更新成功',
            'data': {
                'phone': profile.get_phone_display()
            }
        })

    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': '请求数据格式错误'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': '更新失败，请稍后重试'
        })


@login_required
@require_POST
def update_password(request):
    """
    修改用户密码
    """
    try:
        data = json.loads(request.body)
        current_password = data.get('current_password', '').strip()
        new_password = data.get('new_password', '').strip()
        confirm_password = data.get('confirm_password', '').strip()


        user = authenticate(username=request.user.username, password=current_password)
        if not user:
            return JsonResponse({
                'success': False,
                'message': '当前密码错误'
            })

        # 更新密码
        with transaction.atomic():
            request.user.set_password(new_password)  # 使用set_password而不是make_password
            request.user.save()
            return JsonResponse({
                'success': True,
                'message': '密码修改成功'
            })


    except json.JSONDecodeError:
        return JsonResponse({
            'success': False,
            'message': '请求数据格式错误'
        })
    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': '密码修改失败，请稍后重试'
        })


@login_required
@require_POST
def upload_avatar(request):
    """
    上传用户头像
    """
    try:
        if 'avatar' not in request.FILES:
            return JsonResponse({
                'success': False,
                'message': '请选择头像文件'
            })

        avatar_file = request.FILES['avatar']

        # 验证文件大小（2MB）
        if avatar_file.size > 2 * 1024 * 1024:
            return JsonResponse({
                'success': False,
                'message': '头像文件大小不能超过2MB'
            })

        # 验证文件类型
        allowed_types = ['image/jpeg', 'image/png', 'image/gif']
        if avatar_file.content_type not in allowed_types:
            return JsonResponse({
                'success': False,
                'message': '仅支持JPG、PNG、GIF格式的图片'
            })

        # 生成文件名
        file_extension = os.path.splitext(avatar_file.name)[1]
        filename = f"avatars/{request.user.id}_{datetime.now().strftime('%Y%m%d_%H%M%S')}{file_extension}"

        # 保存文件
        path = default_storage.save(filename, ContentFile(avatar_file.read()))

        # 更新用户头像
        request.user.avatar = path
        request.user.save()

        return JsonResponse({
            'success': True,
            'message': '头像上传成功',
            'data': {
                'avatar_url': request.user.avatar.url if request.user.avatar else None
            }
        })

    except Exception as e:
        return JsonResponse({
            'success': False,
            'message': '头像上传失败，请稍后重试'
        })

